package com.jiong.user.controller;

import com.jiong.common.R;
import com.jiong.user.entity.User;
import com.jiong.user.service.IUserService;
import com.jiong.user.utils.JwtTokenUtils;
import com.jiong.user.vo.LoginVO;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author jiong
 * @since 2025-01-16
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;

    @GetMapping("/list")
    public R list() {
        return R.ok().data("list", userService.list());
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginVO loginVO, HttpServletResponse response) {
        User user = userService.getById(loginVO.getId());
        if (user == null) {
            return R.error().message("Invalid account or password");
        }
        if(!loginVO.getPassword().equals(user.getPassword())) {
            return R.error().message("Invalid account or password");
        }
        // 生成JWT Token
        String token = JwtTokenUtils.createToken(loginVO);

        // 将Token添加到响应头
        response.setHeader("Authorization", "Bearer " + token);
        // 返回结果
        return R.ok().data("token", token);
    }

}
